package org.jeecg.modules.zcgl.tencent.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.HttpClientUtil;
import org.jeecg.modules.zcgl.tencent.config.IWxPayConfig;
import org.jeecg.modules.zcgl.tencent.entity.AttentionInfo;
import org.jeecg.modules.zcgl.tencent.service.IAttentionInfoService;
import org.jeecg.modules.zcgl.tencent.service.IWxPayService;
import org.jeecg.modules.zcgl.tencent.service.IWxTokenService;
import org.jeecg.modules.zcgl.tencent.vo.WxSdkConfigParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@Api(tags="微信公众号")
@RequestMapping("/tencent/wxAuth")
public class WxLoginController {

    @Value("${weChat.getAccessTokenUrl}")
    private String getAccessTokenUrl;
    @Value("${weChat.getUserInfoUrl}")
    private String getUserInfoUrl;
    @Value("${weChat.appId}")
    private String appId;
    @Value("${weChat.secret}")
    private String secret;
    @Value("${weChat.baseUrl}")
    private String baseUrl;

    @Autowired
    private IAttentionInfoService attentionInfoService;
    @Autowired
    private IWxPayService wxPayService;
    @Autowired
    private IWxPayConfig wxPayConfig;
    @Autowired
    private IWxTokenService wxTokenService;

//    @RequestMapping("/login")
//    @CrossOrigin
//    public void wxLogin(HttpServletResponse response) throws IOException {
//        //请求获取code的回调地址
//        //用线上环境的域名或者用内网穿透，不能用ip
//        String callBack = baseUrl + "/tencent/wxAuth/callBack";
//
//        //请求地址
//        String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
//                "?appid=" + appId +
//                "&redirect_uri=" + URLEncoder.encode(callBack, "UTF-8") +
//                "&redirect_uri=" + URLEncoder.encode("http://www.cqukon.com/weChat/", "UTF-8") +
//                "&response_type=code" +
//                "&scope=snsapi_userinfo" +
//                "&state=STATE#wechat_redirect";
//        //重定向
//        response.sendRedirect(url);
//    }

    /**
     *
     * @param code
     * @return
     * @throws IOException
     */
    @ApiOperation(value="获取openID", notes="获取openID")
    @PostMapping("/getOpenId")
//    @RequestMapping("/callBack")
    public Result<?> getOpenId(@RequestParam(name="code",required=true) String code) throws IOException {

        //获取access_token
        String url = getAccessTokenUrl.replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);

        String result = HttpClientUtil.doGet(url);
        log.info("获取openID result:" + result);
        //返回结果的json对象
        JSONObject resultObject = JSON.parseObject(result);
        String opendId =  resultObject.getString("openid");

        if (StringUtils.isNotBlank(opendId)){
            LambdaQueryWrapper<AttentionInfo> queryWrapper = new LambdaQueryWrapper<AttentionInfo>();
            queryWrapper.eq(AttentionInfo :: getOpenid, opendId);
//            queryWrapper.last("");
            AttentionInfo attentionInfo = attentionInfoService.getOne(queryWrapper);
            if (attentionInfo == null){
                attentionInfo = new AttentionInfo();
                attentionInfo.setOpenid(opendId);
                attentionInfoService.save(attentionInfo);
            }

            if (StringUtils.isBlank(attentionInfo.getNickname())){

                try {
                    String infoUrl = getUserInfoUrl.replace("ACCESS_TOKEN", resultObject.getString("access_token")).replace("OPENID", opendId);
                    String infoResult = HttpClientUtil.doGet(infoUrl);
                    log.info("获取USER_INFO result:" + infoResult);
                    JSONObject infoResultObject = JSON.parseObject(infoResult);
                    attentionInfo.setNickname(infoResultObject.getString("nickname"));
                    attentionInfo.setSex(infoResultObject.getInteger("sex"));
                    attentionInfo.setProvince(infoResultObject.getString("province"));
                    attentionInfo.setCity(infoResultObject.getString("city"));
                    attentionInfo.setCountry(infoResultObject.getString("country"));
                    attentionInfo.setHeadimgurl(infoResultObject.getString("headimgurl"));
                    attentionInfo.setPrivilege(infoResultObject.getString("privilege"));
                    attentionInfo.setUnionid(infoResultObject.getString("unionid"));
                    attentionInfoService.updateById(attentionInfo);
                } catch (Exception e) {
//                e.printStackTrace();
                }
            }

            String token = JwtUtil.sign(attentionInfo.getId(), attentionInfo.getOpenid());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("opendId", opendId);
            return Result.ok(map);
        } else {
            return Result.error(null);
        }

    }


    /**
     * 微信支付配置
     */
    @PostMapping(value = "/getSdkConfig")
    public Result<?> getSdkConfig(WxSdkConfigParam param) {
        return Result.ok(wxPayService.wxSdkConfig(param));
    }

    public static void main(String[] args) throws Exception {
        System.out.println(JwtUtil.sign("1288721691103580162", "oFV84xFU-8VAPHBgg8iBj4xFTMvg"));

        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.get(Calendar.YEAR)
                + File.separator + (calendar.get(Calendar.MONTH) + 1)
                + File.separator + calendar.get(Calendar.DATE));

//        HashMap<String, String> data = new HashMap<String, String>();
//        // 商户号
//        data.put("mch_id", "1600980007");
//        // 获取随机字符串
//        data.put("nonce_str", WXPayUtil.generateNonceStr());
//        // 生成签名
//        String KEY = "chongqingzibozichanguanliyouxian";
//        String sign = WXPayUtil.generateSignature(data, KEY);
//        data.put("sign", sign);
//        System.out.println(JSON.toJSONString(data));
//        WXPay wxPay = new WXPay(new IWxPayConfig());
//        String result = wxPay.requestWithoutCert("/sandboxnew/pay/getsignkey", data, 10000, 10000);
//        System.out.println(result);


        BigDecimal bd1 = new BigDecimal( 12911.911);
        String str1 = bd1.setScale(4, BigDecimal.ROUND_HALF_UP).toString();
        System.out.println("str1==="+str1);

        //保留两位小数，不足两位则不补零
        DecimalFormat df2 = new DecimalFormat("###0.##") ;
        System.out.println(df2.format(124.6));
        System.out.println(df2.format(124));

        //添加千位分隔符,保留3位小数，不足的补0
        DecimalFormat df4 = new DecimalFormat("#,##0.000");
        System.out.println(df4.format(new BigDecimal(3613.61)));
        System.out.println(df4.format(new BigDecimal(3613.613)));
        System.out.println(df4.format(new BigDecimal(3613.6135)));
        System.out.println(df4.format(new BigDecimal(3613.6136)));
        System.out.println(URLEncoder.encode("http://www.cqukon.com/weChat", "UTF-8"));

    }
}

